// 好友服务
import { apiService } from './api'
import type { 
  FriendListResponse, 
  SearchFriendsRequest, 
  PaginatedResponse, 
  Friend,
  UserStatus
} from '@/types'

export class FriendService {
  /**
   * 获取好友列表
   */
  async getFriendList(): Promise<FriendListResponse> {
    return apiService.getFriendList()
  }

  /**
   * 搜索好友
   */
  async searchFriends(
    keyword: string, 
    page = 1, 
    pageSize = 20
  ): Promise<PaginatedResponse<Friend>> {
    const request: SearchFriendsRequest = {
      keyword,
      page,
      pageSize
    }
    
    return apiService.searchFriends(request)
  }

  /**
   * 搜索所有匹配的好友（不分页）
   */
  async searchAllFriends(keyword: string): Promise<Friend[]> {
    const allFriends: Friend[] = []
    let page = 1
    let hasMore = true
    
    while (hasMore) {
      try {
        const result = await this.searchFriends(keyword, page, 50)
        allFriends.push(...result.items)
        hasMore = result.hasNext
        page++
      } catch (error) {
        console.error('Error searching friends:', error)
        break
      }
    }
    
    return allFriends
  }

  /**
   * 获取好友在线状态
   */
  async getFriendStatus(userId: number): Promise<{ status: UserStatus; lastActiveTime: Date }> {
    const response = await apiService.getFriendStatus(userId)
    return {
      status: response.status as UserStatus,
      lastActiveTime: new Date(response.lastActiveTime)
    }
  }

  /**
   * 批量获取好友状态
   */
  async getFriendsStatus(userIds: number[]): Promise<Record<number, { status: UserStatus; lastActiveTime: Date }>> {
    const statusMap: Record<number, { status: UserStatus; lastActiveTime: Date }> = {}
    
    // 并发获取所有好友状态
    const promises = userIds.map(async (userId) => {
      try {
        const status = await this.getFriendStatus(userId)
        statusMap[userId] = status
      } catch (error) {
        console.error(`Failed to get status for user ${userId}:`, error)
        // 设置默认状态
        statusMap[userId] = {
          status: 'offline',
          lastActiveTime: new Date()
        }
      }
    })
    
    await Promise.allSettled(promises)
    return statusMap
  }

  /**
   * 发送好友请求
   */
  async sendFriendRequest(userId: number, message?: string): Promise<void> {
    return apiService.sendFriendRequest(userId, message)
  }

  /**
   * 接受好友请求
   */
  async acceptFriendRequest(requestId: number): Promise<void> {
    return apiService.acceptFriendRequest(requestId)
  }

  /**
   * 拒绝好友请求
   */
  async rejectFriendRequest(requestId: number, reason?: string): Promise<void> {
    return apiService.rejectFriendRequest(requestId, reason)
  }

  /**
   * 取消好友请求
   */
  async cancelFriendRequest(requestId: number): Promise<void> {
    return apiService.cancelFriendRequest(requestId)
  }

  /**
   * 获取收到的好友请求
   */
  async getReceivedFriendRequests(page = 1, pageSize = 20): Promise<any> {
    return apiService.getReceivedFriendRequests(page - 1, pageSize)
  }

  /**
   * 获取发送的好友请求
   */
  async getSentFriendRequests(page = 1, pageSize = 20): Promise<any> {
    return apiService.getSentFriendRequests(page - 1, pageSize)
  }

  /**
   * 获取待处理请求数量
   */
  async getPendingRequestCount(): Promise<number> {
    return apiService.getPendingRequestCount()
  }

  /**
   * 检查是否可以发送好友请求
   */
  async canSendFriendRequest(toUserId: number): Promise<boolean> {
    return apiService.canSendFriendRequest(toUserId)
  }

  /**
   * 删除好友
   */
  async removeFriend(userId: number): Promise<void> {
    return apiService.removeFriend(userId)
  }

  /**
   * 获取在线好友列表
   */
  async getOnlineFriends(): Promise<Friend[]> {
    const friendList = await this.getFriendList()
    const onlineFriends = friendList.friends.filter(friend => friend.status === 'online')
    return onlineFriends
  }

  /**
   * 获取离线好友列表
   */
  async getOfflineFriends(): Promise<Friend[]> {
    const friendList = await this.getFriendList()
    const offlineFriends = friendList.friends.filter(friend => friend.status === 'offline')
    return offlineFriends
  }

  /**
   * 根据用户名搜索好友
   */
  async searchFriendsByUsername(username: string): Promise<Friend[]> {
    return this.searchAllFriends(username)
  }

  /**
   * 根据昵称搜索好友
   */
  async searchFriendsByNickname(nickname: string): Promise<Friend[]> {
    return this.searchAllFriends(nickname)
  }

  /**
   * 获取好友详细信息
   */
  async getFriendInfo(userId: number): Promise<Friend | null> {
    try {
      const friendList = await this.getFriendList()
      const friend = friendList.friends.find(f => f.id === userId)
      
      if (friend) {
        // 获取最新状态信息
        const status = await this.getFriendStatus(userId)
        return {
          ...friend,
          status: status.status,
          lastActiveTime: status.lastActiveTime
        }
      }
      
      return null
    } catch (error) {
      console.error('Failed to get friend info:', error)
      return null
    }
  }

  /**
   * 检查是否为好友关系
   */
  async isFriend(userId: number): Promise<boolean> {
    try {
      const friendList = await this.getFriendList()
      return friendList.friends.some(friend => friend.id === userId && friend.isFriend)
    } catch (error) {
      console.error('Failed to check friend relationship:', error)
      return false
    }
  }

  /**
   * 获取好友统计信息
   */
  async getFriendStats(): Promise<{
    totalCount: number
    onlineCount: number
    offlineCount: number
    awayCount: number
  }> {
    try {
      const friendList = await this.getFriendList()
      const friends = friendList.friends
      
      return {
        totalCount: friends.length,
        onlineCount: friends.filter(f => f.status === 'online').length,
        offlineCount: friends.filter(f => f.status === 'offline').length,
        awayCount: friends.filter(f => f.status === 'away').length
      }
    } catch (error) {
      console.error('Failed to get friend stats:', error)
      return {
        totalCount: 0,
        onlineCount: 0,
        offlineCount: 0,
        awayCount: 0
      }
    }
  }

  /**
   * 添加好友（发送好友请求）
   */
  async addFriend(userId: number, message?: string): Promise<void> {
    return this.sendFriendRequest(userId, message)
  }
}

export const friendService = new FriendService()